/*
 * Copyright (C) 2021 Baidu, Inc. All Rights Reserved.
 */
package com.chukun.rpc.consumer;

import java.lang.reflect.Field;
import java.util.LinkedHashMap;
import java.util.Map;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanClassLoaderAware;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.ClassUtils;
import org.springframework.util.ReflectionUtils;

import com.chukun.rpc.consumer.annotation.TinyRpcReference;
import com.chukun.rpc.core.TinyRpcConstants;

import lombok.extern.slf4j.Slf4j;

/**
 * <p>rpc 消费者端处理器<p/>
 *
 * @author chukun
 * @version 1.0
 * @since 1.0-SNAPSHOT
 */
@Slf4j
@Component
public class TinyRpcConsumerPostProcessor implements ApplicationContextAware, BeanClassLoaderAware, BeanFactoryPostProcessor {

    private ApplicationContext context;

    private ClassLoader classLoader;

    private final Map<String, BeanDefinition> rpcRefBeanDefinitions = new LinkedHashMap<>();

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.context = applicationContext;
    }

    @Override
    public void setBeanClassLoader(ClassLoader classLoader) {
       this.classLoader = classLoader;
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        for (String beanDefinitionName : beanFactory.getBeanDefinitionNames()) {
            BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanDefinitionName);
            String beanNameClass = beanDefinition.getBeanClassName();
            if (beanNameClass!= null) {
                Class<?> clazz = ClassUtils.resolveClassName(beanNameClass, classLoader);
                ReflectionUtils.doWithFields(clazz, this::parseRpcReference);
            }
        }
        BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
        rpcRefBeanDefinitions.forEach((beanName, beanDefinition) -> {
            if (context.containsBean(beanName)) {
                throw new IllegalArgumentException("Spring context already has a bean named: " + beanName);
            }
            registry.registerBeanDefinition(beanName, beanDefinition);
            log.info("Registered RpcReferenceBean {} success", beanName);
        });
    }

    /**
     * 处理引用TinyRpcReference注解的字段，添加元数据
     * @param field
     */
    private void parseRpcReference(Field field) {

        TinyRpcReference rpcReference = AnnotationUtils.getAnnotation(field, TinyRpcReference.class);
        if (rpcReference !=null) {
            // 创建TinyRpcReference Bean
            BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(TinyRpcReferenceBean.class);
            builder.setInitMethodName(TinyRpcConstants.INIT_METHOD_NAME);
            builder.addPropertyValue("interfaceClass", field.getType());
            builder.addPropertyValue("version", rpcReference.version());
            builder.addPropertyValue("registryType", rpcReference.registryType());
            builder.addPropertyValue("registryAddr", rpcReference.registryAddress());
            builder.addPropertyValue("timeout", rpcReference.timeout());

            AbstractBeanDefinition beanDefinition = builder.getBeanDefinition();
            rpcRefBeanDefinitions.put(field.getName(), beanDefinition);
        }
    }
}
